package com.xiaobai.auth.config;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xiaobai.common.utils.TokenUtil;
import com.xiaobai.data.manager.system.UserManager;
import com.xiaobai.model.vo.system.login.LoginUser;
import com.xiaobai.model.vo.system.login.LoginVO;
import com.xiaobai.auth.utils.RedisTool;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

/**
 * 自定义认证成功处理器
 */
@Component("loginSuccessHandler")
public class LoginSuccessHandler implements AuthenticationSuccessHandler {


    @Resource
    private RedisTool redisTool;
    @Resource
    private UserManager userManager;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws ServletException, IOException {
        LoginUser user = (LoginUser) authentication.getPrincipal();
        System.out.println("登录成功");
        // 登录成功处理
        //1.生成token
        String token = TokenUtil.generateAccessToken(JSON.parseObject(JSON.toJSONString(user.getUser())));
        String refreshToken = TokenUtil.generateRefreshToken(JSON.parseObject(JSON.toJSONString(user.getUser())));
        long expireTime = TokenUtil.getExpirationTime(token);
        // 配置一下返回给前端的token信息
        LoginVO vo = new LoginVO();
        // 将实体类信息转为JSON
        // TODO 将token存入coookie中 后面加载页面 根据用户的id取查询对应的权限
        // TODO 将token存放到redis中 退出或者修改密码 清空token 获取的时候 也从redis中进行获取
        redisTool.setCacheObject(httpServletRequest.getRemoteAddr(),token, TokenUtil.ACCESS_EXPIRE, TimeUnit.MILLISECONDS);
        vo.setToken(token)
            .setRefreshToken(refreshToken)
            .setExpiresIn(expireTime);
        String res = JSONObject.toJSONString(vo);
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        ServletOutputStream out = httpServletResponse.getOutputStream();
        out.write(res.getBytes(StandardCharsets.UTF_8));
        out.flush();
        out.close();
    }
}

